package com.lineage.list;

import com.lineage.DatabaseFactory;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_SystemMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.utils.SQLUtil;
import com.lineage.server.world.World;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Announcements {
  private static final Log _log = LogFactory.getLog(Announcements.class);
  
  private static Announcements _instance;
  
  private final ArrayList<String> _announcements;
  
  public static Announcements get() {
    if (_instance == null)
      _instance = new Announcements(); 
    return _instance;
  }
  
  private Announcements() {
    this._announcements = new ArrayList<>();
    load();
  }
  
  private void load() {
    Connection co = null;
    PreparedStatement pm = null;
    ResultSet rs = null;
    try {
      co = DatabaseFactory.get().getConnection();
      pm = co.prepareStatement("SELECT * FROM `广播_登入_显示`");
      rs = pm.executeQuery();
      while (rs.next()) {
        int id = rs.getInt("代码");
        if (id >= 5) {
          String message = rs.getString("讯息内容");
          this._announcements.add(message);
        } 
      } 
    } catch (SQLException e) {
      _log.error("message_notice", e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(pm);
      SQLUtil.close(co);
    } 
    _log.info("广播_登入_显示登入公告->" + this._announcements.size());
  }
  
  public void showAnnouncements(L1PcInstance showTo) {
    Iterator<String> iterator = this._announcements.iterator();
    while (iterator.hasNext()) {
      String msg = iterator.next();
      showTo.sendPackets((ServerBasePacket)new S_SystemMessage(msg));
    } 
  }
  
  public void announceToAll(String msg) {
    World.get().broadcastServerMessage(msg);
  }
  
  public ArrayList<String> list() {
    return this._announcements;
  }
}
